package com.huika.renrench.control.common.base;

import java.util.List;

import android.content.Intent;
import android.provider.Settings;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.huika.lib.base.R;
import com.huika.lib.ui.widget.LoadingDialog;
import com.huika.lib.ui.widget.overlay.OverlayLayout;
import com.huika.renrench.http.JSONWrapAjaxParams;
import com.huika.renrench.http.RequestResult;
import com.huika.renrench.http.ServerFlagError;

/**
 * 下拉刷新listview基类
 * @author fanxing 创建于 Mar 18, 2015
 * @param <T>
 */
public abstract class BaseListFrag<T> extends BaseFra implements Listener<RequestResult<List<T>>>{
	protected PullToRefreshListView mPullRefreshListView;
	protected BaseAda adapter;
	protected JSONWrapAjaxParams ajaxParams;
	protected int res_empty_icon = R.drawable.icon_empty;
	protected int res_empty_string = R.string.common_empty_data;
	/**从跟布局中查找PullToRefreshListView，并完成相关操作*/
	protected abstract void initPullListView(View root);
	/**初始加载数据*/
	protected void initLoadData() {
		hideOverLay();
		showLoadingDialog(getString(R.string.common_loading));
		initRequest();
		reloadData();
	}
	
	/**
	 * 请求回调
	 */
	@Override
	public void onResponse(RequestResult<List<T>> result) {
		dismissLoadingDialog();
		mPullRefreshListView.wrapOnRefreshComplete();
		hideOverLay();
		
		int totalSize = result.getTotalSize();
		
		if(CURRENT_PAGE == 1){
			adapter.clearGroup(false);
		}
		
		if(totalSize == 0 && (result.getRs()==null || result.getRs().size()==0)){//无记录
			showOverLayTip(getString(res_empty_string), false);
			onResponseEmpty();
		}else{
			onResponseDate(result);
			adapter.addItems(result.getRs());
		}
		
		changeRefreshMode(totalSize);
	}
	/**请求数据回调结果（数据在设置给adapter之前）*/
	protected void onResponseDate(RequestResult<List<T>> result) {}

	/**请求数据回调结果（数据为空的时候）*/
	protected void onResponseEmpty() {}

	@Override
	public void onErrorResponse(VolleyError error) {
		dismissLoadingDialog();
		if(CURRENT_PAGE == 1 && adapter.getCount()<=0){
			if(error instanceof ServerFlagError){
				showOverLayTip(((ServerFlagError) error).result.msg, false);
			}else{
				showOverLayTip(getString(R.string.common_loading_net_error), true);
			}
		}else{
			showToastMsg(R.string.loading_errors_hint);
		}
		
		mPullRefreshListView.wrapOnRefreshComplete();
	}
	
	protected void showOverLayTip(String str, boolean isError) {
		if(mOverlayLayout == null){
			mOverlayLayout = createEmptyOverLay();
		}
		ViewHolder holder = (ViewHolder) mOverlayLayout.getTag();
		holder.tv_tip.setText(str);
		if(isError){
			holder.tv_reload.setVisibility(View.VISIBLE);
			holder.tv_reload.setOnClickListener(reloaClickListener);
			mOverlayLayout.setOnClickListener(null);
			holder.iv.setImageResource(R.drawable.load_error_icon);
			holder.click_checknetwork.setVisibility(View.VISIBLE);//显示检查网络设置的按钮
		}else{
			holder.tv_reload.setVisibility(View.GONE);
			mOverlayLayout.setOnClickListener(reloaClickListener);
			holder.iv.setImageResource(res_empty_icon);
			holder.click_checknetwork.setVisibility(View.GONE);//隐藏掉检查网络设置的按钮
		}
		
		showOverLay();
	}
	
	/**
	 * 更改刷新模式
	 * @param totalSize
	 * @author FAN 创建于Nov 27, 2014
	 */
	private void changeRefreshMode(int totalSize) {
		if(totalSize == 0){
			mPullRefreshListView.setMode(Mode.DISABLED);
		}else if(adapter.getCount() >= totalSize){
			mPullRefreshListView.setMode(Mode.PULL_FROM_START);
		}else{
			mPullRefreshListView.setMode(Mode.BOTH);
		}
	}
	
	/**
	 * 创建列表为空的overlay
	 * @return
	 * @author FAN 创建于Dec 2, 2014
	 */
	protected OverlayLayout createEmptyOverLay(){
		OverlayLayout overlayLayout = new OverlayLayout(getActivity());
		overlayLayout.attachTo(mPullRefreshListView.getRefreshableView());
		overlayLayout.setOverlayView(R.layout.common_load_error);
		
		ImageView iv = (ImageView) overlayLayout.getOverlayView().findViewById(R.id.load_error_icon);
		
		TextView tv_tip = (TextView) overlayLayout.getOverlayView().findViewById(R.id.load_error_tip);
		TextView tv_reload = (TextView) overlayLayout.getOverlayView().findViewById(R.id.click_reload);
		
		ViewHolder holder = new ViewHolder();
		holder.tv_reload = tv_reload;
		holder.tv_tip = tv_tip;
		holder.iv = iv;
		holder.click_checknetwork = overlayLayout.getOverlayView().findViewById(R.id.click_checknetwork);
		holder.click_checknetwork.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// 检查网络设置
				Intent intent= new Intent(Settings.ACTION_SETTINGS);
                startActivity(intent);
			}
		});
		overlayLayout.setTag(holder);
		
		return overlayLayout;
	}
	
	public class ViewHolder{
		View click_checknetwork;
		TextView tv_tip, tv_reload;
		ImageView iv;
	}
	
	private View.OnClickListener reloaClickListener = new View.OnClickListener() {
		
		@Override
		public void onClick(View v) {
			//第一页就加载失败了
			hideOverLay();
//			mPullRefreshListView.setFirstRefreshing();
			showLoadingDialog(getString(R.string.common_loading));
			reloadData();
		}
	};
	
	@Override
	public void showLoadingDialog(String parameter) {
		if (null == loadingDialog) {
			loadingDialog = new LoadingDialog(getActivity());
			loadingDialog.setOnCancelListener(this);
		}
		loadingDialog.setTitle(parameter);
		if(!loadingDialog.isShowing())
			loadingDialog.show();
	}

	public abstract void reloadData();
	public abstract void initRequest();
}
